package cn.gwm.flink.streaming.function.map;

import cn.gwm.flink.streaming.constant.ChargePredictFields;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.RichMapFunction;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author : GW00280745
 * @date : 2022/6/23 17:03
 * @description : 结果数据标准化
 * 怎么办？通过配置文件生成结果即hdfs数据，hive外部表字段的comment有依据。好处是能清洗各个字段的来龙去脉。
 * 具体做法？ 配置文件可以指定输出哪些字段，同时还能指定字段类型。即这个配置文件等价表结构。
 */
public class ChargePredictResStandardMapFunction extends RichMapFunction {
    private JSONObject fieldJson;
    public ChargePredictResStandardMapFunction(JSONObject fieldJson){
        this.fieldJson = fieldJson;
    }
    private String blankStr = "";
    @Override
    public Object map(Object value) throws Exception {
        JSONObject line = (JSONObject) value;
        JSONObject jsonObject = new JSONObject();
        //key是标准化字段 value是中间结果字段
        for (Map.Entry<String, Object> entry : fieldJson.entrySet()) {
            jsonObject.put(entry.getKey(),line.getOrDefault(entry.getValue(), blankStr));
        }
        //特殊字段处理
        fieldProcess(jsonObject);
        return jsonObject;
    }

    private void fieldProcess(JSONObject line) {
        roundHalfUp(line, ChargePredictFields.ins().srcFieldBmsBatterCurrRm,2);
        roundHalfUp(line, ChargePredictFields.ins().stdFieldBatterMapValue,2);
    }

    private void roundHalfUp(JSONObject line,String field,int scaleVal) {
        BigDecimal bigDecimal = line.getBigDecimal(field);
        if (bigDecimal == null){return;}
        BigDecimal scale = bigDecimal.setScale(scaleVal, BigDecimal.ROUND_HALF_UP);
        line.put(field,scale);
    }
}
